package com.qf.openapi.web.master.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.DigestUtil;
import com.qf.openapi.web.master.dao.UserDao;
import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.ex.UserException;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.vo.UserRegistVo;
import com.qf.openapi.web.master.vo.UserUpdateVo;
import com.qf.openapi.web.master.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Value("${file.upload.path}")
    String fileUploadPath;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User getUser(Integer id) {
        return userDao.getUserById(id);
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User login(String username, String password) {

        //1. 根据用户名查询用户信息
        User user =  userDao.getUserByName(username);

        if (user == null){  // 没用匹配的用户，直接返回null
            return null;
        }else {
            //2. 比对密码是否正确
            final String dbpassword = user.getPassword();

            // 转换 password 为 md5 字符串
            final String md5password = DigestUtil.md5Hex(password);

            if (dbpassword.equals(md5password)){
                return user;
            }

            return null;
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void registUser(UserRegistVo userRegistVo) throws Exception {
        //1.保存文件到指定目录
        MultipartFile photo = userRegistVo.getPhoto();

        //生成一个唯一的文件名
        String prefix = UUID.randomUUID().toString();
        String fileName = prefix + "_" + photo.getOriginalFilename();

        String finalFilePath = fileUploadPath + fileName;

        photo.transferTo(new File(finalFilePath));
        log.debug("上传头像成功,finalFilePath={}",finalFilePath);

        //检查用户名是否存在
        String username = userRegistVo.getUsername();
        User dbuser = userDao.getUserByName(username);
        if (dbuser!=null){
            //用户名重复
            throw new UserException(-1001,"用户重复");

        }
        //2.把用户的数据写入数据库表
        User user = new User();

        user.setName(userRegistVo.getUsername());
        String password = userRegistVo.getPassword();
        //password--->md5
        String md5Password = DigestUtil.md5Hex(password);
        user.setPassword(md5Password);

        user.setSex(userRegistVo.getSex());
        user.setBirthday(userRegistVo.getDate());

        user.setRegistTime(new Date());
        user.setPhotopath(fileName);

        userDao.insertUser(user);
        log.debug("用户数据落库成功,user={}",user);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<User> getAllUser(Integer page, Integer limit) {
        return userDao.getUserAll(page,limit);
    }
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public int getAllCount() {
        return userDao.getAllCount();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser(UserVo userVo) throws UserException {
        //检查用户名是否存在
        String name = userVo.getName();
        User userByName = userDao.getUserByName(name);
        if (userByName!=null){
            //用户名重复
            throw new UserException();

        }
        //2.把用户的数据写入数据库表
        User user = new User();

        user.setName(userVo.getName());
        String password = userVo.getPassword();
        //password--->md5
        String md5Password = DigestUtil.md5Hex(password);
        user.setPassword(md5Password);
        user.setSex(userVo.getSex());
        user.setBirthday(userVo.getBirthday());
        user.setRegistTime(userVo.getRegistTime());

        userDao.addUser(user);
        log.debug("用户数据落库成功,user={}",user);

    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUser(UserUpdateVo userUpdateVo) {
        String birthday = userUpdateVo.getBirthday();
        String registTime = userUpdateVo.getRegistTime();
        Long birLong = Long.valueOf(birthday);
        Long regLong = Long.valueOf(registTime);
        Date birth = new Date(birLong);
        Date regist = new Date(regLong);
        User user = new User(Integer.valueOf(userUpdateVo.getId()), userUpdateVo.getName(),  userUpdateVo.getPassword(),userUpdateVo.getSex(), birth, regist);
        userDao.updateUser(user);
    }

    @Override
    public void delUser(String[] ids) {
        for (String id : ids) {
            Integer integer = Integer.valueOf(id);
            userDao.delUser(integer);
        }
    }
}
